using System.Collections.Generic;
using UnityEditor.Profiling;
using UnityEditorInternal;

namespace SGEngine.ProfilerEx
{
    public class ProfilerExUtility
    {
        public class FrameThreadDesc
        {
            public string GroupName;
            public string ThreadName;
            public int ThreadIndex;
            public override string ToString()
            {
                return $"GroupName:{GroupName} ThreadName:{ThreadName} ThreadIndex:{ThreadIndex}";
            }
        }
        
        public const int k_CallNumColumnIdx = 3;
        public const int k_GCColumnIdx = 4;
        public const int k_TimeMsColumnIdx = 5;
        public const int k_SelfMsColumnIdx = 6;
        
        public static HierarchyFrameDataView GetFrameDataView(int frameIdx, int threadIndex)
        {
            HierarchyFrameDataView.ViewModes viewMode = HierarchyFrameDataView.ViewModes.MergeSamplesWithTheSameName | HierarchyFrameDataView.ViewModes.HideEditorOnlySamples;
            int profilerSortColumn = k_GCColumnIdx;
            return ProfilerDriver.GetHierarchyFrameDataView(frameIdx, threadIndex, viewMode, profilerSortColumn, false);
        }

        /// <summary>
        /// 获取所有线程
        /// </summary>
        /// <param name="frameIdx"></param>
        /// <returns></returns>
        public static List<FrameThreadDesc> GetAllThreadListByFrameIdx(int frameIdx)
        {
            List<FrameThreadDesc> threadItems = new List<FrameThreadDesc>();
            using (var frameIterator = new ProfilerFrameDataIterator())
            {
                var threadCount = frameIterator.GetThreadCount(frameIdx);
                for (var i = 0; i < threadCount; ++i)
                {
                    frameIterator.SetRoot(frameIdx, i);
                    var grp = frameIterator.GetGroupName();
                    var thrd = frameIterator.GetThreadName();
                    
                    threadItems.Add(new FrameThreadDesc()
                    {
                        GroupName = grp,
                        ThreadName = thrd,
                        ThreadIndex = i
                    });
                }
            }
            return threadItems;
        }
        
    }
}